<template>
  <div>
      <el-card>
      <div slot="header">
        <my-breadcrumb>个人设置</my-breadcrumb>
      </div>

      <el-row>
        <el-col :span="16">
            <!-- 表单 -->
            <el-form label-width="80px" :model="userInfo" :rules="rules" ref="user">
              <el-form-item label="编号">
                <span>{{userInfo.id}}</span>
              </el-form-item>
               <el-form-item label="手机">
                <span>{{userInfo.mobile}}</span>
              </el-form-item>
               <el-form-item label="名称" prop="name">
                <el-input v-model="userInfo.name" />
              </el-form-item>
               <el-form-item label="简介" prop="intro">
                <el-input type="textarea" v-model="userInfo.intro" />
              </el-form-item>
               <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfo.email" />
              </el-form-item>
              <el-form-item>
                <el-button @click="hUpdateUserInfo" type="primary">保存设置</el-button>
              </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="8">
            <el-upload
              class="avatar-uploader"
              action=""
              :http-request="hUpload"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload">
                <el-image v-if="userInfo.photo" :src="userInfo.photo" class="avatar"/>
                <!-- 没有上传之前，这里是一个大大的 + -->
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 表单验证对象
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 7, message: '用户名长度在1,7之间', trigger: 'blur' }
        ],
        intro: [
          { required: true, message: '请输入个人介绍', trigger: 'blur' },
          { min: 1, max: 20, message: '用户名长度在1,20之间', trigger: 'blur' }
        ],
        email: [
          {
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: '请输入合法的email',
            trigger: 'blur'
          }
        ]
      },
      uploadImageUrl: '',
      // uploadImageUrl: '../assets/default.png', // 图片按钮
      headers: {
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      },
      userInfo: {
        name: 'xxxx',
        intro: '',
        email: '',
        id: '',
        mobile: '',
        photo: ''
      }
    }
  },
  methods: {
    async getUserInfo () {
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/profile',
          method: 'GET'
        })
        console.log(res);
        this.userInfo.name = res.data.data.name
        this.userInfo.email = res.data.data.email
        this.userInfo.id = res.data.data.id
        this.userInfo.intro = res.data.data.intro
        this.userInfo.mobile = res.data.data.mobile
        this.userInfo.photo = res.data.data.photo
      } catch (err) {
        console.log(err);
      }
    },
    buildData () {
      const data = {
        name: this.userInfo.name,
        intro: this.userInfo.intro,
        email: this.userInfo.email
      }
      return data
    },
    async doUpdateUserInfo () {
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/profile',
          method: 'PATCH',
          data: this.buildData()
        })
        console.log(res);
        this.$message.success('修改用户信息成功')
        // 抛出自定义事件，将新用户名传给layout组件
        this.$eventBus.$emit('mod-user', {
          newName: res.data.data.name
        })
      } catch (err) {
        console.log(err);
        this.$message.error('修改用户信息失败')
      }
    },
    hUpdateUserInfo () {
      this.$refs.user.validate(valid => {
        if (valid) {
          this.doUpdateUserInfo()
        }
      })
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      // file.size 单位是字节
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async hUpload (config) {
      const fd = new FormData()
      fd.append('photo', config.file)
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/photo',
          method: 'PATCH',
          data: fd
        })
        console.log(res);
        this.$message.success('上传成功')
        this.userInfo.photo = res.data.data.photo
        // 抛出自定义事件，将新头像的url传给layout组件
        this.$eventBus.$emit('mod-user', {
          newPhoto: res.data.data.photo
        })
      } catch (err) {
        console.log(err);
        this.$message.error('上传失败')
      }
    }
  },
  created () {
    this.getUserInfo()
  }
}
</script>

<style lang="less" scoped>

.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #ddd;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
